package com.example.auth.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.example.auth.mapper.OAuthClientMapper;
import com.example.auth.model.entity.OAuthClient;
import com.example.auth.service.OAuthClientService;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.Arrays;
import java.util.List;

/**
 * OAuth2客户端服务实现类
 */
@Service
public class OAuthClientServiceImpl extends ServiceImpl<OAuthClientMapper, OAuthClient> implements OAuthClientService {

    /**
     * 根据客户端ID查询客户端信息
     *
     * @param clientId 客户端ID
     * @return 客户端信息
     */
    @Override
    public OAuthClient getByClientId(String clientId) {
        return baseMapper.selectByClientId(clientId);
    }

    /**
     * 校验客户端凭证
     *
     * @param clientId 客户端ID
     * @param clientSecret 客户端密钥
     * @return 是否有效
     */
    @Override
    public boolean validateClientCredentials(String clientId, String clientSecret) {
        OAuthClient client = getByClientId(clientId);
        return client != null && client.getClientSecret().equals(clientSecret);
    }

    /**
     * 校验重定向URI是否合法
     *
     * @param clientId 客户端ID
     * @param redirectUri 重定向URI
     * @return 是否合法
     */
    @Override
    public boolean validateRedirectUri(String clientId, String redirectUri) {
        OAuthClient client = getByClientId(clientId);
        if (client == null || !StringUtils.hasText(client.getRedirectUri())) {
            return false;
        }
        
        List<String> allowedUris = Arrays.asList(client.getRedirectUri().split(","));
        return allowedUris.contains(redirectUri);
    }
} 